using System.Collections.Generic;
using RG.Common.Configuration;

namespace RG.Common.Configuration
{
    public interface IApplicationSettings
    {
        void Bind(string settingsKey, object obj);
        void Save();
        void Load();
    }

    public static class IApplicationSettings_Ext
    {
        public static void BindToTypeGUID(this IApplicationSettings s, object obj)
        {
            s.Bind(obj.GetType().GUID.ToString(), obj);
        }

        public static void BindToTypeName(this IApplicationSettings s, object obj)
        {
            s.Bind(obj.GetType().Name, obj);
        }
    }

    public class ApplicationSettings : ApplicationSettingsBase
    {
        public static IEnumerable<ISetting> CollectByAttribute(object from, string parentObjName)
        {
            var collected = new List<ISetting>();
            foreach (var pi in from.GetType().GetProperties())
            {
                var settingAttributes = (BaseSettingsAttribute[])pi.GetCustomAttributes(typeof(BaseSettingsAttribute), true);

                foreach (var attribute in settingAttributes)
                {
                    var settings = attribute.Collect(from, parentObjName, pi);
                    foreach (var setting in settings)
                    {
                        collected.Add(setting);
                    }
                }
            }
            return collected;
        }

        protected override IEnumerable<ISetting> CollectSettings(object from)
        {
            return CollectByAttribute(from, null);
        }
    }
}
